<template>
  <div class="music-info">
    <!-- 搜索版块 -->
    <div class="search_box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="资讯标题">
          <el-input placeholder="标题" v-model="searchInfo" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                searchInfo = '';
                set();
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="list_box_but1">
      <el-button
        type="primary"
        @click="
          dialogFormVisible = true;
          operate = 1;
        "
        >新增资讯</el-button
      >
    </div>

    <div class="list_box1">
      <div class="list_table">
        <el-table
          size="small"
          :data="data"
          :height="tableHeight"
          stripe
          :header-cell-style="{ background: '#EEF1F6' }"
        >
          <!-- <el-table-column type="selection" width="40"></el-table-column> -->
          <el-table-column
            label="ID"
            prop="id"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column label="资讯图片" width="110" align="center">
            <template v-slot="scope">
              <div
                style="
                  width: 80px;
                  height: 80px;
                  overflow: hidden;
                  display: inline-block;
                "
              >
                <img :src="getUrl(scope.row.imgUrl)" style="width: 100%" />
              </div>
              <el-upload
                ref="uploadRef"
                class="upload"
                :action="getUrl('/mv/upload')"
                :data="{ type: 'musicInfo' }"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="(response:any) => updateInfo(response, scope.row.id)"
              >
                <el-button>更新图片</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            label="标题"
            prop="title"
            width="150"
          ></el-table-column>
          <el-table-column label="详情" prop="detail">
            <template v-slot="scope">
              <el-scrollbar height="100px">
                <p>{{ scope.row.detail }}</p>
              </el-scrollbar>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template v-slot="scope">
              <el-button @click="editRow(scope.row)">编辑</el-button>
              <el-popconfirm
                title="删除不可恢复，是否确定删除?"
                @confirm="deleteRow(scope.row.id)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="list_pagination">
      <el-pagination
        class="pagination"
        background
        layout="total, prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <el-dialog
      v-model="dialogFormVisible"
      :title="operate ? '添加资讯' : '修改资讯'"
      width="500"
      center
      :destroy-on-close="true"
      @close="clearInfo"
    >
      <el-form ref="formRef" :model="infoForm" :hide-required-asterisk="true">
        <el-form-item
          prop="title"
          label="资讯标题"
          :rules="{
            required: true,
            message: '标题不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.title" />
        </el-form-item>
        <el-form-item
          prop="detail"
          label="资讯详情"
          :rules="{
            required: true,
            message: '详情不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.detail" :rows="5" type="textarea" />
        </el-form-item>
        <el-form-item label="资讯图片">
          <el-upload
            class="avatar-uploader"
            ref="uploadRef"
            :action="getUrl('/mv/upload')"
            :auto-upload="true"
            :show-file-list="false"
            :data="{ type: 'musicInfo' }"
            :on-success="uploadSuccess"
          >
            <img
              v-if="infoForm.imgUrl"
              :src="getUrl(infoForm.imgUrl)"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel(formRef)">取消</el-button>
          <el-button type="primary" @click="submit(formRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import {
  getMusicInfo,
  addMusicInfo,
  updateMusicInfo,
  delMusicInfo,
} from "@/api";
import { getUrl } from "@/utils copy/format";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

const formRef = ref<FormInstance>();
const tableData = ref([]); // 记录歌曲，用于显示
const currentPage = ref(1);
const pageSize = ref(10);
const operate = ref(1);
const dialogFormVisible = ref(false);
const infoForm = ref({
  title: "",
  detail: "",
  imgUrl: "",
});
let operateId: number;
const data = ref([]);
const tableHeight = ref(0);
const searchInfo = ref("");
tableHeight.value = window.innerHeight - 205;
async function updateInfo(response: any, id: number) {
  await updateMusicInfo({ id, imgUrl: response.data });
  set();
}
const uploadSuccess = (response: any) => {
  infoForm.value.imgUrl = response.data;
};
const submit = (formEl: any) => {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      if (operate.value) {
        res = await addMusicInfo(infoForm.value);
      } else {
        res = await updateMusicInfo({ ...infoForm.value, id: operateId });
      }
      console.log(res);
      set();
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
const cancel = (formEl: any) => {
  dialogFormVisible.value = false;
  infoForm.value = {
    title: "",
    detail: "",
    imgUrl: "",
  };
  formEl.resetFields();
};
const clearInfo = () => {
  infoForm.value = {
    title: "",
    detail: "",
    imgUrl: "",
  };
};
const editRow = (row: any) => {
  operate.value = 0;
  infoForm.value = {
    title: row.title,
    detail: row.detail,
    imgUrl: row.imgUrl,
  };
  operateId = row.id;
  dialogFormVisible.value = true;
};
const deleteRow = async (InformationId: number) => {
  const res = await delMusicInfo(InformationId);
  set();
};
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
  getData();
};
async function handleSearch() {
  currentPage.value = 1;
  tableData.value = data.value = await getMusicInfo(searchInfo.value.trim());
}
function getData() {
  searchInfo.value = "";
  data.value = tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
}
async function set() {
  currentPage.value = 1;
  tableData.value = [];
  const singers = await getMusicInfo("");
  tableData.value = singers;
  getData();
}
onMounted(() => {
  set();
});
</script>

<style lang="scss" scoped>
@import "@/static/css/common.scss";

svg {
  width: 14px;
  height: 14px;
  fill: #fff;
  margin-right: 4px;
}

:deep(.el-table__cell) {
  border-bottom: none !important;
}

.inner_icon {
  fill: #4d70ff;
  margin-right: 2px;
}

.inner_icon:hover {
  fill: #2d56fa;
}

.music-info {
  padding-bottom: 10px;
}

.list_box1 {
  text-indent: 0;
  background: #fff;
  border-radius: 4px;
  overflow: auto;
}

.list_box_but,
.list_table {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
}

.list_box_but1 {
  position: absolute;
  top: 18px;
  right: 30px;
}

.list_box_but a {
  color: #fff;
}

.list_pagination {
  //padding-top: 14px;
  text-indent: 0;

  > div {
    justify-content: flex-end;
    margin-right: 20px;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
